/*
This file is part of buco.  
Copyright (c) 2012 Christopher Pawelzik <christopher@cpawelzik.com>

Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php 
*/ 
package buco.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringWriter;

import org.json.simple.*;
import org.json.simple.parser.*;

import buco.core.api.*;

import javax.servlet.ServletException;
import javax.servlet.http.*;

public class JsonRpcServlet extends CompositionServlet {
	
  /**
	 * 
	 */
	private static final long serialVersionUID = -4086717183310276342L;	

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{				
		// Get composition context 
		CompositionContext compositionCtx = getOrCreateComposition(request.getSession());
		// Set content type
		response.setContentType("application/json; charset=UTF-8");		
		// Get the request object		
		JSONObject requestObj = readRequestObject(request);
		// Invoke method and generate response object 		
		Dispatcher dispatcher = new Dispatcher(compositionCtx);
		JSONObject responseObj = dispatcher.dispatch(requestObj); 
		if(responseObj != null) { 
			// Send response object as string
			StringWriter out = new StringWriter();
			try {
				responseObj.writeJSONString(out);
			} catch (IOException e) {			
				e.printStackTrace();
				response.sendError(500); 
			}
			response.getWriter().write(out.toString());
		}
		else
		{
			// Problem! 
			response.sendError(500); 
		}
	}		
		
	private JSONObject readRequestObject(HttpServletRequest request) throws IOException {
		BufferedReader reader = request.getReader();
		char[] buffer = new char[1024];
		int count = 0; 
		StringBuffer sb = new StringBuffer(); 		
		
		while((count = reader.read(buffer)) > 0) {
			sb.append(buffer, 0, count); 
		}		
		
		JSONParser parser=new JSONParser();
		try {
			return (JSONObject) parser.parse(sb.toString());
		} catch (ParseException e) {			
			e.printStackTrace();
			return null;
		}
	}
}
